﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utilities.Shell
{
    public class ComposedInstruction : IRunnable
    {
        public Scope Scope { get; private set; }
        public List<IRunnable> Instructions { get; private set; }

        public ComposedInstruction(Scope scope, string instruction)
        {
            Scope = scope;
            Instructions = new List<IRunnable>();

            List<string> instructions = instruction.Split('>').Select(i => i.Trim()).ToList();
            foreach (string i in instructions)
                if (i == "(")
                    Instructions.Add(new Scope(Scope.Shell, Scope));
                else
                    Instructions.Add(new Instruction(scope, i));
        }

        public void Run(string replacement)
        {
            string[] results = new string[] { "" };

            foreach (IRunnable i in Instructions)
                results = results.SelectMany(r => Shell.GetResult(i.Run, r).SplitLines()).ToArray();

            if (results.Count() > 0)
                Console.WriteLine(string.Join(Environment.NewLine, results));
        }
    }
}
